package com.ncloud.auth.config;

import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import com.alibaba.fastjson.JSONObject;
import com.ncloud.auth.service.TokenConfig;
import com.ncloud.auth.util.JWT;
import com.ncloud.common.exception.UserException;
import com.ncloud.common.utils.RedisUtils;

import io.jsonwebtoken.Claims;
@Configuration
public class LocalWebAppConfigurer extends WebMvcConfigurerAdapter{
	@Autowired
	private RedisUtils redisUtils;
	@Autowired
	private TokenConfig tokenConfig;
	@Bean
	public FilterRegistrationBean corsFilter() {
		UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
		CorsConfiguration config = new CorsConfiguration();
		config.setAllowCredentials(true);
		config.addAllowedOrigin("*");
		config.addAllowedHeader("*");
		config.addAllowedMethod("*");
		source.registerCorsConfiguration("/**", config);
		FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
		bean.setOrder(0);
		return bean;
	}
	public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(authTokenInterceptor()).excludePathPatterns("/**/export**", "/batch/upload", "/upload",
        		"/auth", "/auth/**", "/v2/api-docs", "/swagger-resources", "/swagger-resources/**").addPathPatterns("/**");
//        这个exclude没用了，不过留下了。
    }
    @Bean
    public HandlerInterceptor authTokenInterceptor(){
    	return new HandlerInterceptor() {
    		public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
    	            throws Exception {
    			String token = request.getHeader(Constant.HEAD_TOKEN);
    			boolean authenSuccess = true;
    			JSONObject obj = new JSONObject();
    			String userID = null;
    			String roundId = null;
    			if (token == null || "".equals(token)) {
    				throw new UserException(1701, "认证TOKEN为空！");
    			}
    			if (authenSuccess) {
        			Claims claims = JWT.parseJWT(token);
        			userID = claims.get("userID", String.class);
        			roundId = claims.get("roundId", String.class);
        			String redisToken = redisUtils.getString(tokenConfig.getTokenName(userID,roundId));
        			
        			Date expired = claims.getExpiration();
        			if(expired.getTime() < new Date().getTime() || token == null || "".equals(token) || redisToken == null || "".equals(redisToken)) {
        				throw new UserException(1702, "TOKEN已失效！");
        			}
    			}
    			if ( !authenSuccess) {
        			PrintWriter writer = response.getWriter();
        			writer.write(obj.toJSONString());
        			return false;
    			}
    			request.setAttribute("userID", userID);
    			redisUtils.expire(tokenConfig.getUserInfoName(userID,roundId),Constant.refreshTokenExpiredTime);
    			redisUtils.expire(tokenConfig.getRefreshTokenName(userID,roundId),Constant.refreshTokenExpiredTime);
//    			这里要比较token对不对
    	        return true;
    	    }
    	    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
    	            ModelAndView modelAndView) throws Exception {
    	    }

    	    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
    	            throws Exception {
    	    }
		};
    }
    
    
}
